<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport"
          content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"/>
    <title>安详</title>
    <link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css"/>
    <link rel="stylesheet" type="text/css" href="/static/plugins/webuploader/webuploader.css"/>
    <link rel="stylesheet" type="text/css" href="/static/common/common.css"/>
    <link rel="stylesheet" type="text/css" href="https://g.alicdn.com/de/prismplayer/2.8.7/skins/default/aliplayer-min.css"/>

    <style type="text/css">
        .receive-message-list {
            border: 1px solid #1e9fff;
            width: 900px;
            height: 300px;
            overflow-y: auto;
        }

        .layui-timeline-item {
            margin-top: 10px;
        }

        .layui-show.user-all-list p {
            height: 34px;
            line-height: 34px;
            font-size: 16px;
            border-bottom: 1px solid #ddd;
            cursor: pointer;
            margin-bottom: 10px;
            padding-right: 5px;
            padding-left: 5px;
        }

        .layui-show.user-all-list p:hover {
            background-color: #ddd;
            color: #1e9fff;
        }

        .im-ul-container {

        }

        .im-ul-container .im-li-item {
            float: left;
            margin: 5px 5px;
            width: 300px;
        }

        .im-friend-name {
            width: 90px;
            display: inline-block;
        }

        .im-friend-name-size {
            width: 45px;
            display: inline-block;
        }

        .im-friend-item-list p {
            height: 34px;
            line-height: 34px;
            font-size: 16px;
            border-bottom: 1px solid #ddd;
            cursor: pointer;
            margin-bottom: 10px;
            padding-right: 5px;
            padding-left: 5px;
        }

        .im-friend-item-list p span {
            width: 130px;
            display: inline-block;
        }

        .im-friend-item-list p:hover {
            background-color: #ddd;
            color: #1e9fff;
        }

        .layim-chat-logs-main {
            height: 280px;
            padding: 15px 15px 5px;
            overflow-x: hidden;
            overflow-y: auto;
            border: 1px solid #ddd;
        }

        .layim-chat-logs-main ul .layim-chat-mine {
            text-align: right;
            padding-left: 0;
            padding-right: 60px;
        }

        .layim-chat-logs-main ul li {
            position: relative;
            font-size: 0;
            margin-bottom: 10px;
            padding-left: 60px;
            min-height: 68px;
        }

        .layim-chat-mine .layim-chat-user {
            left: auto;
            right: 3px;
        }

        .layim-chat-user {
            position: absolute;
            left: 3px;
        }

        .layim-chat-user img {
            width: 40px;
            height: 40px;
            border-radius: 100%;
        }

        .layim-chat-mine .layim-chat-user cite {
            left: auto;
            right: 60px;
            text-align: right;
        }

        .layim-chat-user cite {
            position: absolute;
            left: 60px;
            top: -2px;
            width: 500px;
            line-height: 24px;
            font-size: 12px;
            white-space: nowrap;
            color: #999;
            text-align: left;
            font-style: normal;
        }

        .layim-chat-mine .layim-chat-user cite i {
            padding-left: 0;
            padding-right: 15px;
        }

        .layim-chat-user cite i {
            padding-left: 15px;
            font-style: normal;
        }

        .layim-chat-text, .layim-chat-user {
            display: inline-block;
            *display: inline;
            *zoom: 1;
            vertical-align: top;
            font-size: 14px;
        }

        .layim-chat-text {
            position: relative;
            line-height: 22px;
            margin-top: 25px;
            padding: 8px 15px;
            background-color: #e2e2e2;
            border-radius: 3px;
            color: #333;
            word-break: break-all;
            max-width: 462px \9;
        }

        fieldset {
            margin-top: 10px !important;
            margin-bottom: 10px !important;
        }
    </style>

</head>
<body class="body-container">

<legend>serene聊天系统</legend>

<div style="height: 160px;">
    <div class="layui-card-body layui-text" style="width: 90%; float: left;">
        <table class="layui-table">
            <tbody>
            <tr>
                <td>serene聊天系统</td>
                <td>webSocket、netty4、springboot、mybatis-puls、mysql8.0、layui、jquery ：已完成简单功能： 1、登陆
                    ;2、群消息发送;3、好友单独发消息、可同时多个好友发送
                </td>
                <td>已完成简单功能： 1、登陆 ;2、群消息发送;3、好友单独发消息、可同时多个好友发送</td>
            </tr>
            <tr>
                <td>功能介绍</td>
                <td>只要给加班费,当牛做马无所谓<span style="font-size: 18px; font-weight: 700;">#</span></td>
                <td>作者：serene</td>
            </tr>
            </tbody>
        </table>
    </div>

    <div class="layui-card-body layui-text" style="width: 40%; float: left;">

    </div>
</div>

<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>serene聊天系统</legend>
</fieldset>

<div style="height: 800px;">
    <ul class="im-ul-container">
        <li class="im-li-item" style="margin-top: 12px;">
            <button type="button" class="layui-btn layui-btn-normal add-user-info-btn">添加User</button>
            <div class="layui-collapse" lay-accordion="" style="width: 240px;margin: 10px 0px;">
                <div class="layui-colla-item">
                    <h2 class="layui-colla-title">User列表&nbsp;&nbsp;<span class="user-all-list-size">0/0</span></h2>
                    <div class="layui-colla-content layui-show user-all-list">
                    </div>
                </div>
            </div>
        </li>

        <li class="im-li-item" style="width: 356px; margin-top: -14px;">
            <p class="im-connect-status" style="font-size: 22px; padding: 20px 0px;display: inline-block;">im未连接...</p>
            <button type="button" class="layui-btn layui-btn-normal im-login-btn">Im-登录</button>
            <button type="button" class="layui-btn layui-btn-danger im-login-out-btn" style="display: none;">Im-退出
            </button>

            <div style="margin: 5px 0px;">
                <form class="layui-form" action="">
                    <div class="layui-form-item layim-chat-logs-main" style="margin-bottom: 5px;height: 328px;">
                        <ul class="im-chat-msg-logs-to-group">

                        </ul>
                    </div>
                    <div class="layui-form-item layui-form-text">
                        <div class="layui-input-block" style="margin-left: 0px;">
                            <textarea style="resize:none;min-height: 70px;" name="sedGroupMsg" placeholder="请输入发送内容"
                                      class="layui-textarea"></textarea>
                        </div>
                    </div>

                    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm send-group-btn"
                            style="float: right;background-color: #00c1de;">发送群信息
                    </button>

                </form>
            </div>
        </li>

        <li class="im-li-item im-friend-container-li" style="display: none; margin: 49px 5px; width: 264px;">
            <!-- <button type="button" class="layui-btn layui-btn-normal add-friend-info-btn">添加好友</button>
            <button type="button" class="layui-btn layui-btn-normal im-friend-request-review-btn" >Im-好友申请--<span>0</span></button> -->
            <div class="layui-collapse" lay-accordion="" style="width: 300px;margin: 10px 0px;">
                <div class="layui-colla-item">
                    <h2 class="layui-colla-title">
                        <span class="im-friend-name">我的好友</span>
                        <span class="im-friend-name-size">5/10</span>

                        <!-- 编辑好友组 -->
                        <!-- <button type="button" class="layui-btn layui-btn-normal layui-btn-sm">
                        <i class="layui-icon"></i>
                        </button>

                        <button type="button" class="layui-btn layui-btn-danger layui-btn-sm"><i class="layui-icon">
                        </i>
                        </button> -->

                    </h2>
                    <div class="layui-colla-content layui-show im-friend-item-list">
                        <!-- <p class="open-friend-btn" >
                        <span class="friend-info-btn" user-id="123456789">哈哈哈</span> -->
                        <!-- 编辑好友 -->
                        <!-- <button type="button" class="layui-btn layui-btn-normal layui-btn-sm edit-friend-btn">
                        <i class="layui-icon"></i>
                        </button> -->
                        <!-- 删除好友 -->
                        <!-- <button type="button" class="layui-btn layui-btn-danger layui-btn-sm delete-friend-btn">
                        <i class="layui-icon"></i>
                        </button>
                        </p>	 -->
                    </div>
                </div>
            </div>
        </li>
    </ul>
</div>

<div id="bdtts_div_id">
    <audio id="tts_autio_id" autoplay="autoplay">
        <source id="tts_source_id" src="http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=9&text=播报内容"
                type="audio/mpeg">
        <embed id="tts_embed_id" height="0" width="0" src="">
    </audio>
</div>

<script src="/static/jquery/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="/static/layui/layui.all.js" type="text/javascript"></script>
<script src="/static/admin/index.js" type="text/javascript"></script>
<script src="/static/plugins/webuploader/webuploader.js" type="text/javascript"></script>
<script src="/static/common/common.js" type="text/javascript"></script>
<script type="text/javascript" src="https://g.alicdn.com/de/prismplayer/2.8.7/aliplayer-min.js"></script>
<script type="text/javascript" th:inline="none">

    var imChatUser = null;
    var wsWebSocketUrl = "ws://192.168.3.8:8080/ws";
    window.onload = function () {
        // 显示广告信息
        //showYunFuWuQiInfo();

        selectAllUserList();
    }


    // 发送群信息
    $(document).on('click', '.send-group-btn', function () {
        var sedGroupMsg = $("textarea[name='sedGroupMsg']").val()
        if (!sedGroupMsg) {
            layer.msg("不能发送空白消息");
        }
        if (imChatUser == null) {
            layer.msg("请登录后再发送,im未连接....");
        }
        IM_CHAT.chatSendGroupMsg(sedGroupMsg);
    })


    // 好友申请记录  im-friend-request-review-btn
    $(document).on('click', '.im-friend-request-review-btn', function () {
        var imUser = imChatUser.user;
        $.ajax({
            url: '/imChatFriendRequestLogs/selectRequestLogsList', // 请求的url地址
            dataType: 'json', 						// 返回格式为json
            data: {'userId': imUser.id},
            type: 'post', 							// 请求方式
            async: false,
            success: function (res) {
                if (res.code == 200) {
                    var requestLogsList = res.data;
                    var html = "";
                    html += '<div style="margin: 40px 20px;">';
                    html += '<table class="layui-table">';
                    html += '<thead>';
                    html += '<tr>';
                    html += '<th>昵称</th>';
                    html += '<th>申请时间</th>';
                    html += '<th>申请备注</th>';
                    html += '<th>请求状态</th>';
                    html += '<th>操作</th>';
                    html += '</tr>';
                    html += '</thead>';
                    html += '<tbody>';
                    for (var i = 0; i < requestLogsList.length; i++) {
                        var obj = requestLogsList[i];
                        html += '<tr>';
                        html += '<td>' + obj.nickname + '</td>';
                        html += '<td>' + commonDateFormat(obj.createTime, "yyyy-MM-dd hh:mm:ss") + '</td>';
                        html += '<td>' + obj.requestRemark + '</td>';

                        // requestStatus 请求状态     1、通过     2、已拒绝   3、申请中
                        var requestStatusMsg = "";
                        if (obj.requestStatus == 1) {
                            requestStatusMsg = "通过";
                        } else if (obj.requestStatus == 2) {
                            requestStatusMsg = "拒绝";
                        } else if (obj.requestStatus == 3) {
                            requestStatusMsg = "申请中";
                        }
                        html += '<td>' + requestStatusMsg + '</td>';
                        html += '<td>';
                        if (obj.requestStatus == 3) {
                            html += '<button type="button" class="layui-btn layui-btn-xs layui-btn-normal update-request-status-one-btn" request-id=' + obj.id + '>通过</button>';
                            html += '<button type="button" class="layui-btn layui-btn-xs layui-btn-danger update-request-status-two-btn" request-id=' + obj.id + '>拒绝</button>';
                        }
                        html += '</td>';
                        html += '</tr>';
                    }

                    html += '</tbody>';
                    html += '</table>';


                    html += '</div>';

                    var index = layer.open({
                        type: 1,				  		// 0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层
                        title: "好友申请记录",					// title: ['文本', 'font-size:18px;']，数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
                        area: ['700px', '500px'],		// 默认：'auto' 	自适应
                        //shade: 1,				  		// 要想显示遮罩需要将这个  注释
                        skin: 'layui-layer-lan',  		// layer内置的skin有：layui-layer-lan layui-layer-molv
                        //maxmin: true,
                        resize: false,
                        shadeClose: true,
                        content: html,
                        btn: ['取消'],
                        btn1: function () {
                            layer.close(index);
                        },
                        cancel: function () {

                        },
                        success: function (layers) {

                        }
                    });
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function () {

            }
        });
    })

    // 好友通过
    $(document).on('click', '.update-request-status-one-btn', function () {
        var requestId = $(this).attr("request-id");
        layer.confirm('确定通过好友吗？', {
            btn: ['确定', '取消']		//按钮
        }, function (index) {
            $.ajax({
                url: '/imChatFriendRequestLogs/updateRequestStatus', 				// 请求的url地址
                dataType: 'json', 						// 返回格式为json
                data: {'requestId': requestId, 'updateStatus': 1},
                type: 'post', 							// 请求方式
                async: false,
                success: function (res) {
                    if (res.code == 200) {
                        layer.msg("通过成功");

                        layer.close(index);
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function () {

                }
            });
        });
    })

    // 好友拒绝
    $(document).on('click', '.update-request-status-two-btn', function () {
        var requestId = $(this).attr("request-id");
        layer.confirm('确定拒绝好友吗？', {
            btn: ['确定', '取消']		//按钮
        }, function (index) {
            $.ajax({
                url: '/imChatFriendRequestLogs/updateRequestStatus', 				// 请求的url地址
                dataType: 'json', 						// 返回格式为json
                data: {'requestId': requestId, 'updateStatus': 2},
                type: 'post', 							// 请求方式
                async: false,
                success: function (res) {
                    if (res.code == 200) {
                        layer.msg("拒绝成功");
                        layer.close(index);
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function () {

                }
            });
        });
    })

    // 点击好友 显示聊天窗口
    $(document).on('click', '.open-friend-btn .friend-info-btn', function () {
        var friendUserId = $(this).attr("friend-user-id");

        var html = "";
        html += '<div style="margin: 40px 20px;">';
        html += '<form class="layui-form" action="">';

        // 聊天记录
        html += '<div class="layui-form-item layim-chat-logs-main friend-user-id-' + friendUserId + '" style="height: 130px;">';
        html += '<ul class="im-chat-msg-logs-to-receive-friend-user-id-' + imChatUser.user.id + friendUserId + '">';


        html += '</ul>';
        html += '</div>';

        // 发送内容
        html += '<div class="layui-form-item layui-form-text">';
        html += '<div class="layui-input-block" style="margin-left: 0px;">';
        html += '<textarea style="resize:none;" name="sedMsg" placeholder="请输入发送内容" class="layui-textarea sed-msg-friend-user-id-' + friendUserId + '"></textarea>';
        html += '</div>';
        html += '</div>';

        html += '</form>';
        html += '</div>';

        var friendUserInfo = null;
        for (var i = 0; i < all_user_list_cache.length; i++) {
            var obj = all_user_list_cache[i];
            if (obj.id == friendUserId) {
                friendUserInfo = obj;
                break;
            }
        }

        var index = layer.open({
            type: 1,				  						// 0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层
            title: "好友-" + friendUserInfo.nickname,		// title: ['文本', 'font-size:18px;']，数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
            area: ['25%', '70%'],							// 默认：'auto' 	自适应
            //shade: 1,				  						// 要想显示遮罩需要将这个  注释
            skin: 'layui-layer-lan',  						// layer内置的skin有：layui-layer-lan layui-layer-molv
            maxmin: true,
            resize: true,
            shadeClose: false,
            shade: false,
            content: html,
            btn: ['发送', '关闭'],
            btn1: function () {

            },
            btn2: function () {
                layer.close(index);
            },
            cancel: function () {

            },
            success: function (layers) {
                var form = layui.form;
                layers.addClass('layui-form');

                // 查询好友聊天记录
                selectFriendLogsList(friendUserId);

                //	将按钮弄成能提交的
                layers.find('.layui-layer-btn0').attr('lay-filter', 'sendFriendInfoFrom').attr('lay-submit', '');
                layers.find('.layui-layer-btn0').attr('friend-user-id-btn', friendUserId);

                form.render();
                form.on('submit(sendFriendInfoFrom)', function (data) {
                    //
                    var fUserIdVal = $(this).attr("friend-user-id-btn");
                    console.log(data.field.sedMsg)
                    var msg = data.field.sedMsg;
                    IM_CHAT.chatSendMsg(msg, fUserIdVal);
                    return false;
                });

            }
        });
    })

    // 修改好友
    $(document).on('click', '.open-friend-btn .edit-friend-btn', function () {
        layer.msg("功能待开发中....");

    })

    // 删除好友
    $(document).on('click', '.open-friend-btn .delete-friend-btn', function () {
        layer.confirm('确定删除好友吗？', {
            btn: ['确定', '取消']		//按钮
        }, function (index) {
            layer.close(index);
            layer.msg("功能待开发中....");
        });
    })

    // 添加用户		add-user-info-btn
    $(document).on('click', '.add-user-info-btn', function () {
        layer.msg("这个很简单,自己完成吧.....");

    })

    // 添加好友		add-friend-info-btn
    $(document).on('click', '.add-friend-info-btn', function () {
        var html = "";
        html += '<div style="margin: 40px 20px;">';
        html += '<form class="layui-form edit-info-from" action="">';

        html += '<div class="layui-form-item">';
        html += '<div class="layui-inline">';
        html += '<label class="layui-form-label zdy-required">手机号</label>';
        html += '<div class="layui-input-inline">';
        html += '<input type="tel" name="phone" lay-verify="required" maxlength="12" placeholder="请输入手机号"  autocomplete="off" class="layui-input">';
        html += '</div>';
        html += '</div>';
        html += '</div>';

        html += '</form>';
        html += '</div>';

        var index = layer.open({
            type: 1,				  		// 0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层
            title: "im-添加好友",					// title: ['文本', 'font-size:18px;']，数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
            area: ['500px', '300px'],		// 默认：'auto' 	自适应
            //shade: 1,				  		// 要想显示遮罩需要将这个  注释
            skin: 'layui-layer-lan',  		// layer内置的skin有：layui-layer-lan layui-layer-molv
            maxmin: true,
            resize: false,
            shadeClose: false,
            content: html,
            btn: ['立即添加', '取消'],
            btn1: function () {

            },
            btn2: function () {
                layer.close(index);
            },
            cancel: function () {

            },
            success: function (layers) {
                var form = layui.form;
                layers.addClass('layui-form');
                //	将按钮弄成能提交的
                layers.find('.layui-layer-btn0').attr('lay-filter', 'addFriendFrom').attr('lay-submit', '');

                form.render();
                form.on('submit(addFriendFrom)', function (data) {
                    var imUser = imChatUser.user;
                    var dataQuery = {
                        phone: data.field.phone,
                        mainUserId: imUser.mainUserId,
                        userId: imUser.id
                    }
                    $.ajax({
                        url: '/imChatFriendRequestLogs/addInfo', 				// 请求的url地址
                        dataType: 'json', 						// 返回格式为json
                        data: dataQuery,
                        type: 'post', 							// 请求方式
                        async: false,
                        success: function (res) {
                            if (res.code == 200) {
                                layer.msg("好友申请成功,请耐心等待");
                                layer.close(index);
                            } else {
                                layer.msg(res.msg);
                            }
                        },
                        error: function () {

                        }
                    });
                    return false;
                });

            }
        });
    })

    // 用户列表缓存
    var my_friend_list_cache = [];

    // 获得用户列表
    function selectMyFriendList(userId) {
        my_friend_list_cache = [];
        $.ajax({
            url: '/imChatFriendInfo/selectFriendList',  	// 请求的url地址
            dataType: 'json', 					// 返回格式为json
            data: {'userId': userId},
            type: 'post', 						// 请求方式
            async: false,
            success: function (res) {
                var html = "";
                if (res.code == 200) {
                    my_friend_list_cache = res.data;

                    for (var i = 0; i < res.data.length; i++) {
                        var obj = res.data[i];

                        html += '<p class="open-friend-btn" >';
                        html += '<span class="friend-info-btn" friend-user-id=' + obj.friendUserId + '>' + obj.nickname + '</span>';
                        <!-- 编辑好友 -->
                        html += '<button type="button" class="layui-btn layui-btn-normal layui-btn-sm edit-friend-btn" friend-user-id=' + obj.friendUserId + '>';
                        html += '<i class="layui-icon"></i>';
                        html += '</button>';
                        <!-- 删除好友 -->
                        html += '<button type="button" class="layui-btn layui-btn-danger layui-btn-sm delete-friend-btn" friend-user-id=' + obj.friendUserId + '>';
                        html += '<i class="layui-icon"></i>';
                        html += '</button>';
                        html += '</p>';
                    }
                } else {
                    layer.msg(res.msg);
                }
                $(".im-friend-name-size").html(0 + " / " + res.data.length);
                $(".im-friend-item-list").empty().append(html);
            },
            error: function () {

            }
        });
    }

    // 登录
    $(document).on('click', '.im-login-btn', function () {
        var html = "";
        html += '<div style="margin: 40px 20px;">';
        html += '<form class="layui-form edit-info-from" action="">';

        html += '<div class="layui-form-item">';
        html += '<div class="layui-inline">';
        html += '<label class="layui-form-label zdy-required">手机号</label>';
        html += '<div class="layui-input-inline">';
        html += '<input type="tel" name="phone" lay-verify="required" maxlength="12" autocomplete="off" class="layui-input" value="11111111111">';
        html += '</div>';
        html += '</div>';
        html += '</div>';

        html += '<div class="layui-form-item">';
        html += '<div class="layui-inline">';
        html += '<label class="layui-form-label zdy-required">密码</label>';
        html += '<div class="layui-input-inline">';
        html += '<input type="text" name="password" lay-verify="required" maxlength="16" autocomplete="off" class="layui-input" value="123456">';
        html += '</div>';
        html += '</div>';
        html += '</div>';

        html += '</form>';
        html += '</div>';

        var index = layer.open({
            type: 1,				  		// 0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层
            title: "im-登录",					// title: ['文本', 'font-size:18px;']，数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
            area: ['500px', '300px'],		// 默认：'auto' 	自适应
            //shade: 1,				  		// 要想显示遮罩需要将这个  注释
            skin: 'layui-layer-lan',  		// layer内置的skin有：layui-layer-lan layui-layer-molv
            maxmin: true,
            resize: false,
            shadeClose: false,
            content: html,
            btn: ['立即登录', '取消'],
            btn1: function () {

            },
            btn2: function () {
                layer.close(index);
            },
            cancel: function () {

            },
            success: function (layers) {
                var form = layui.form;
                layers.addClass('layui-form');
                //	将按钮弄成能提交的
                layers.find('.layui-layer-btn0').attr('lay-filter', 'imLoginFrom').attr('lay-submit', '');

                form.render();
                form.on('submit(imLoginFrom)', function (data) {
                    $.ajax({
                        url: '/imChat/login',  				// 请求的url地址
                        dataType: 'json', 					// 返回格式为json
                        data: data.field,
                        type: 'post', 						// 请求方式
                        async: false,
                        success: function (res) {
                            if (res.code == 200) {
                                // 缓存用户信息
                                imChatUser = res.data;
                                // 初始化连接
                                IM_CHAT.init();
                                // 登录成功  隐藏登录按钮
                                $(".im-login-btn").hide();
                                $(".im-login-out-btn").show();
                                // im-friend-container-li
                                $(".im-friend-container-li").show();
                                layer.msg("连接成功");
                                //selectMyFriendList(imChatUser.user.id);


                                var html2 = "";
                                for (var i = 0; i < all_user_list_cache.length; i++) {
                                    var obj = all_user_list_cache[i];
                                    if (obj.id != imChatUser.user.id) {
                                        html2 += '<p class="open-friend-btn" >';
                                        html2 += '<span class="friend-info-btn" friend-user-id=' + obj.id + '>' + obj.nickname + '</span>';
                                        //<!-- 编辑好友 -->
                                        html2 += '<button type="button" class="layui-btn layui-btn-normal layui-btn-sm edit-friend-btn" friend-user-id=' + obj.friendUserId + '>';
                                        html2 += '<i class="layui-icon"></i>';
                                        html2 += '</button>';
                                        //<!-- 删除好友 -->
                                        html2 += '<button type="button" class="layui-btn layui-btn-danger layui-btn-sm delete-friend-btn" friend-user-id=' + obj.friendUserId + '>';
                                        html2 += '<i class="layui-icon"></i>';
                                        html2 += '</button>';
                                        html2 += '</p>';
                                    }
                                }
                                $(".im-friend-name-size").html(all_user_list_cache.length + " / " + all_user_list_cache.length);
                                $(".im-friend-item-list").empty().append(html2);

                                layer.close(index)
                            } else {
                                layer.msg(res.msg);
                            }
                        },
                        error: function () {

                        }
                    });
                    return false;
                });

            }
        });
    });

    // 退出im
    $(document).on('click', '.im-login-out-btn', function () {
        layer.confirm('确定退出im吗？', {
            btn: ['确定', '取消']		//按钮
        }, function (index) {
            layer.close(index);
            window.location.href = "/imChat/showImChatInfo";
            //layer.msg("功能待开发中....");
        });
    });

    // 显示用户信息	whow-user-info-btn
    $(document).on('click', '.whow-user-info-btn', function () {
        var userIdVal = $(this).attr("user-id");
        var userObj = null;
        for (var i = 0; i < all_user_list_cache.length; i++) {
            var obj = all_user_list_cache[i];
            if (obj.id == userIdVal) {
                userObj = obj;
            }
        }

        var html = "";
        html += '<div style="margin: 40px 20px;">';
        html += '<form class="layui-form edit-info-from" action="">';

        html += '<div class="layui-form-item">';
        html += '<div class="layui-inline">';
        html += '<label class="layui-form-label zdy-required">昵称</label>';
        html += '<div class="layui-input-inline">';
        html += '<input type="tel" name="phone" lay-verify="required" maxlength="12" autocomplete="off" class="layui-input" value=' + userObj.nickname + '>';
        html += '</div>';
        html += '</div>';
        html += '</div>';

        html += '<div class="layui-form-item">';
        html += '<div class="layui-inline">';
        html += '<label class="layui-form-label zdy-required">手机号</label>';
        html += '<div class="layui-input-inline">';
        html += '<input type="tel" name="phone" lay-verify="required" maxlength="12" autocomplete="off" class="layui-input" value=' + userObj.phone + '>';
        html += '</div>';
        html += '</div>';
        html += '</div>';

        html += '<div class="layui-form-item">';
        html += '<div class="layui-inline">';
        html += '<label class="layui-form-label zdy-required">密码</label>';
        html += '<div class="layui-input-inline">';
        html += '<input type="text" name="password" lay-verify="required" maxlength="16" autocomplete="off" class="layui-input" value=' + userObj.password + '>';
        html += '</div>';
        html += '</div>';
        html += '</div>';

        html += '</form>';
        html += '</div>';

        var index = layer.open({
            type: 1,				  		// 0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层
            title: "用户信息",					// title: ['文本', 'font-size:18px;']，数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
            area: ['700px', '500px'],		// 默认：'auto' 	自适应
            //shade: 1,				  		// 要想显示遮罩需要将这个  注释
            skin: 'layui-layer-lan',  		// layer内置的skin有：layui-layer-lan layui-layer-molv
            //maxmin: true,
            resize: false,
            shadeClose: true,
            content: html,
            btn: ['取消'],
            btn1: function () {
                layer.close(index);
            },
            cancel: function () {

            },
            success: function (layers) {

            }
        });
    });

    // 用户列表缓存
    var all_user_list_cache = [];

    // 获得用户列表
    function selectAllUserList() {
        all_user_list_cache = [];
        $.ajax({
            url: '/sysUser/selectAllList',  	// 请求的url地址
            dataType: 'json', 					// 返回格式为json
            data: {},
            type: 'post', 						// 请求方式
            async: false,
            success: function (res) {
                var html = "";
                if (res.code == 200) {
                    all_user_list_cache = res.data;
                    for (var i = 0; i < res.data.length; i++) {
                        var obj = res.data[i];
                        html += '<p class="whow-user-info-btn" user-id=' + obj.id + '>' + obj.phone + " - " + obj.nickname + '</p>';
                    }
                } else {
                    layer.msg(res.msg);
                }
                $(".layui-colla-title .user-all-list-size").html(res.data.length + " / " + res.data.length);
                $(".user-all-list").empty().append(html);
            },
            error: function () {

            }
        });
    }

    window.IM_CHAT = {
        socket: null,
        init: function () {
            if (window.WebSocket) {
                IM_CHAT.socket = new WebSocket(wsWebSocketUrl);
                IM_CHAT.socket.onopen = function () {
                    $(".im-connect-status").text("im连接成功.." + imChatUser.user.nickname);
                    IM_CHAT.chatConnect();
                },
                    IM_CHAT.socket.onclose = function () {
                        $(".im-connect-status").text("连接关闭.." + imChatUser.user.nickname);
                    },
                    IM_CHAT.socket.onerror = function () {
                        $(".im-connect-status").text("发生错误.." + imChatUser.user.nickname);
                    },
                    IM_CHAT.socket.onmessage = function (e) {
                        console.log("接受到消息：" + e.data);
                        var dataContent = JSON.parse(e.data);
                        var action = dataContent.action;
                        var chatMsg = dataContent.chatMsg;
                        var msgContent = chatMsg.msgContent;
                        // 发送者id
                        var sendId = chatMsg.sendId;
                        var sendTime = chatMsg.sendTime;
                        // 接受者id
                        var receiveId = chatMsg.receiveId;

                        var html = "";
                        var sendNickname = "";
                        if (imChatUser.user.id == sendId) {
                            // 自己发的
                            html += '<li class="layim-chat-mine"> ';
                            html += '<div class="layim-chat-user">';
                            html += '<img src="' + imChatUser.user.pictureUrl + '">';
                            html += '<cite><i>' + commonDateFormat(sendTime, "yyyy-MM-dd hh:mm:ss") + '</i>' + imChatUser.user.nickname + '</cite>';
                            html += '</div>';
                            html += '<div class="layim-chat-text" style="background-color: #00c1de;color: #efeff4;">' + msgContent + '</div>';
                            html += '</li>';
                        } else {
                            for (var i = 0; i < all_user_list_cache.length; i++) {
                                var obj = all_user_list_cache[i];
                                if (obj.id == sendId) {
                                    // 收到别人发的
                                    html += '<li>';
                                    html += '<div class="layim-chat-user">';
                                    html += '<img src="' + obj.pictureUrl + '">';
                                    html += '<cite>' + obj.nickname + '<i>' + commonDateFormat(sendTime, "yyyy-MM-dd hh:mm:ss") + '</i></cite>';
                                    html += '</div>';
                                    html += '<div class="layim-chat-text">' + msgContent + '</div>';
                                    html += '</li>';
                                    sendNickname = obj.nickname;
                                    break;
                                }
                            }
                        }
                        // 2, "聊天消息"	7, "群消息"
                        if (action == 2) {
                            if (imChatUser.user.id == sendId) {
                                $(".im-chat-msg-logs-to-receive-friend-user-id-" + sendId + receiveId).append(html);
                                $(".layim-chat-logs-main.friend-user-id-" + receiveId).scrollTop($(".layim-chat-logs-main.friend-user-id-" + receiveId)[0].scrollHeight);
                                $(".sed-msg-friend-user-id-" + receiveId).val("");
                            } else {
                                $(".im-chat-msg-logs-to-receive-friend-user-id-" + receiveId + sendId).append(html);
                                $(".layim-chat-logs-main.friend-user-id-" + sendId).scrollTop($(".layim-chat-logs-main.friend-user-id-" + sendId)[0].scrollHeight);
                                //$(".sed-msg-friend-user-id-"+receiveId).val("");
                                voicePlaying("好友消息： " + sendNickname + " 发送了, 内容为： " + msgContent)
                            }
                        } else if (action == 7) {
                            $(".im-chat-msg-logs-to-group").append(html);
                            $(".layui-form-item.layim-chat-logs-main").scrollTop($(".layui-form-item.layim-chat-logs-main")[0].scrollHeight);
                            if (imChatUser.user.id == sendId) {
                                $("textarea[name='sedGroupMsg']").val("")
                            } else {
                                // 群消息
                                voicePlaying("群消息： " + sendNickname + " 发送了, 内容为： " + msgContent)
                            }
                        }
                    }
            } else {
                alert("浏览器不支持websocket协议...");
            }
        },
        chatConnect: function () {
            if (!imChatUser) {
                layer.msg("请先登录,获取用户失败");
                return false;
            }
            var chatMsgObj = {
                sendId: imChatUser.user.id,	// 发送者的用户id
                receiveId: "",				// 接受者的用户id
                msgContent: "",				// 聊天内容
                msgId: ""					// 用于消息的签收
            }
            var msgObj = {
                action: 1,			// CONNECT(1, "第一次(或重连)初始化连接"), CHAT(2, "聊天消息"), SIGNED(3, "消息签收"),
                // KEEPALIVE(4, "客户端保持心跳"), PULL_FRIEND(5, "拉取好友");
                chatMsg: chatMsgObj,	// 用户的聊天内容entity
                extand: ""			// 扩展字段
            }
            var msgObjJson = JSON.stringify(msgObj);
            IM_CHAT.socket.send(msgObjJson);

            // 查询 群信息列表
            selectGroupLogsList(1);
        },
        chatSendMsg: function (msg, rId) {
            if (!imChatUser) {
                layer.msg("请先登录,获取用户失败");
                return false;
            }
            if (!msg) {
                layer.msg("消息不能为空");
                return false;
            }
            var chatMsgObj = {
                sendId: imChatUser.user.id,		// 发送者的用户id
                receiveId: rId,					// 接受者的用户id
                msgContent: msg,					// 聊天内容
                msgId: ""						// 用于消息的签收
            }
            var msgObj = {
                action: 2,						// CONNECT(1, "第一次(或重连)初始化连接"), CHAT(2, "聊天消息"), SIGNED(3, "消息签收"),
                // KEEPALIVE(4, "客户端保持心跳"), PULL_FRIEND(5, "拉取好友");
                chatMsg: chatMsgObj,				// 用户的聊天内容entity
                extand: ""						// 扩展字段
            }
            var msgObjJson = JSON.stringify(msgObj);
            IM_CHAT.socket.send(msgObjJson);
        },
        chatSendGroupMsg: function (msg) {
            if (!imChatUser) {
                layer.msg("请先登录,获取用户失败");
                return false;
            }
            if (!msg) {
                layer.msg("消息不能为空");
                return false;
            }
            var chatMsgObj = {
                sendId: imChatUser.user.id,		// 发送者的用户id
                receiveId: "",					// 接受者的用户id
                msgContent: msg,					// 聊天内容
                msgId: ""						// 用于消息的签收
            }
            var msgObj = {
                action: 7,			// CONNECT(1, "第一次(或重连)初始化连接"), CHAT(2, "聊天消息"), SIGNED(3, "消息签收"),
                // KEEPALIVE(4, "客户端保持心跳"), PULL_FRIEND(5, "拉取好友");
                chatMsg: chatMsgObj,	// 用户的聊天内容entity
                extand: ""			// 扩展字段
            }
            var msgObjJson = JSON.stringify(msgObj);
            IM_CHAT.socket.send(msgObjJson);
        },
    };

    // 查询群聊天记录
    function selectGroupLogsList(groupId) {
        $.ajax({
            url: '/imChatMsgLogs/selectGroupLogsList',  				// 请求的url地址
            dataType: 'json', 					// 返回格式为json
            data: {'groupInfoId': groupId},
            type: 'post', 						// 请求方式
            async: false,
            success: function (res) {
                if (res.code == 200) {
                    var html = "";
                    for (var b = 0; b < res.data.length; b++) {
                        var logObj = res.data[b];
                        var sendTime = logObj.sendTime;
                        var msgContent = logObj.msgContent;
                        if (imChatUser.user.id == logObj.sendId) {
                            // 自己发的
                            html += '<li class="layim-chat-mine"> ';
                            html += '<div class="layim-chat-user">';
                            html += '<img src="' + imChatUser.user.pictureUrl + '">';
                            html += '<cite><i>' + commonDateFormat(sendTime, "yyyy-MM-dd hh:mm:ss") + '</i>' + imChatUser.user.nickname + '</cite>';
                            html += '</div>';
                            html += '<div class="layim-chat-text" style="background-color: #00c1de;color: #efeff4;">' + msgContent + '</div>';
                            html += '</li>';
                        } else {
                            for (var i = 0; i < all_user_list_cache.length; i++) {
                                var obj = all_user_list_cache[i];
                                if (obj.id == logObj.sendId) {
                                    // 收到别人发的
                                    html += '<li>';
                                    html += '<div class="layim-chat-user">';
                                    html += '<img src="' + obj.pictureUrl + '">';
                                    html += '<cite>' + obj.nickname + '<i>' + commonDateFormat(sendTime, "yyyy-MM-dd hh:mm:ss") + '</i></cite>';
                                    html += '</div>';
                                    html += '<div class="layim-chat-text">' + msgContent + '</div>';
                                    html += '</li>';
                                    break;
                                }
                            }
                        }
                    }
                    $(".im-chat-msg-logs-to-group").append(html);
                    $(".layui-form-item.layim-chat-logs-main").scrollTop($(".layui-form-item.layim-chat-logs-main")[0].scrollHeight);
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function () {

            }
        });
    }

    // 查询好友聊天记录
    function selectFriendLogsList(receiveId) {
        $.ajax({
            url: '/imChatMsgLogs/selectFriendLogsList',  				// 请求的url地址
            dataType: 'json', 					// 返回格式为json
            data: {'sendId': imChatUser.user.id, 'receiveId': receiveId},
            type: 'post', 						// 请求方式
            async: false,
            success: function (res) {
                if (res.code == 200) {
                    var html = "";
                    for (var b = 0; b < res.data.length; b++) {
                        var logObj = res.data[b];
                        var sendTime = logObj.sendTime;
                        var msgContent = logObj.msgContent;
                        if (imChatUser.user.id == logObj.sendId) {
                            // 自己发的
                            html += '<li class="layim-chat-mine"> ';
                            html += '<div class="layim-chat-user">';
                            html += '<img src="' + imChatUser.user.pictureUrl + '">';
                            html += '<cite><i>' + commonDateFormat(sendTime, "yyyy-MM-dd hh:mm:ss") + '</i>' + imChatUser.user.nickname + '</cite>';
                            html += '</div>';
                            html += '<div class="layim-chat-text" style="background-color: #00c1de;color: #efeff4;">' + msgContent + '</div>';
                            html += '</li>';
                        } else {
                            for (var i = 0; i < all_user_list_cache.length; i++) {
                                var obj = all_user_list_cache[i];
                                if (obj.id == logObj.sendId) {
                                    // 收到别人发的
                                    html += '<li>';
                                    html += '<div class="layim-chat-user">';
                                    html += '<img src="' + obj.pictureUrl + '">';
                                    html += '<cite>' + obj.nickname + '<i>' + commonDateFormat(sendTime, "yyyy-MM-dd hh:mm:ss") + '</i></cite>';
                                    html += '</div>';
                                    html += '<div class="layim-chat-text">' + msgContent + '</div>';
                                    html += '</li>';
                                    break;
                                }
                            }
                        }
                    }
                    // im-chat-msg-logs-to-receive-friend-user-id-1995
                    $(".im-chat-msg-logs-to-receive-friend-user-id-" + imChatUser.user.id + receiveId).append(html);
                    $(".layim-chat-logs-main.friend-user-id-" + receiveId).scrollTop($(".layim-chat-logs-main.friend-user-id-" + receiveId)[0].scrollHeight);
                    //$(".sed-msg-friend-user-id-"+receiveId).val("");
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function () {

            }
        });
    }

    // 登录	im-chat-login-btn
    $(document).on('click', '.im-chat-login-btn', function () {
        var phone = $("input[name='phone']").val();
        var password = $("input[name='password']").val();
        imChatLogin(phone, password);
    })

    // 登录获得用户信息
    function imChatLogin(p, pw) {
        if (!p) {
            layer.msg("手机号不能为空");
            return false;
        }
        if (!pw) {
            layer.msg("密码不能为空");
            return false;
        }
        $.ajax({
            url: '/imChat/login',  				// 请求的url地址
            dataType: 'json', 					// 返回格式为json
            data: {'phone': p, 'password': pw},
            type: 'post', 						// 请求方式
            async: false,
            success: function (res) {
                if (res.code == 200) {
                    // 缓存用户信息
                    imChatUser = res.data;
                    // 初始化连接
                    IM_CHAT.init();
                    // 登录成功不显示登录账号
                    $(".logn-operation").empty().append("");
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function () {

            }
        });
    }

    // 发送消息
    $(document).on('click', '.send-msg-btn', function () {
        var message = $("input[name='message']").val();
        IM_CHAT.chatSendMsg(message);
    })


    // 语音播放
    function voicePlaying(text) {
        var ttsDiv = document.getElementById('bdtts_div_id');
        var ttsAudio = document.getElementById('tts_autio_id');
        // 这样就可实现播放内容的替换了
        //ttsDiv.removeChild(ttsAudio);
        var au1 = '<audio id="tts_autio_id" autoplay="autoplay">';
        var sss = '<source id="tts_source_id" src="http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=' + text + '" type="audio/mpeg">';
        var eee = '<embed id="tts_embed_id" height="0" width="0" src="">';
        var au2 = '</audio>';
        ttsDiv.innerHTML = au1 + sss + eee + au2;
        ttsAudio = document.getElementById('tts_autio_id');
        ttsAudio.play();
    }
</script>
</body>

</html>